package gpstools.data;

import generated.ped.CalendarItem;
import generated.ped.ExerciseData;
import generated.ped.PolarExerciseData;
import generated.ped.Result;
import generated.ped.Sample;
import generated.ped.SampleType;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class PolarData {
	private final PolarExerciseData data;

	public PolarData(PolarExerciseData data) {
		this.data = data;
	}

	public Date getDate() {
		ExerciseData exercise = getExcercise();

		if (exercise == null)
			return null;

		try {
			/* 2013-04-15 14:52:22.0 */
			return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.US).parse(exercise.getTime());
		} catch (ParseException e) {
			throw new RuntimeException(e);
		}
	}

	private ExerciseData getExcercise() {
		List<CalendarItem> noteOrFitnessDataOrExercise = data.getCalendarItems().getNoteOrFitnessDataOrExercise();
		ExerciseData exercise = null;
		for (CalendarItem calendarItem : noteOrFitnessDataOrExercise) {
			if (calendarItem instanceof ExerciseData) {
				exercise = (ExerciseData) calendarItem;
				break;
			}
		}
		return exercise;
	}

	public List<Short> getHeartRateList() {
		ExerciseData exercise = getExcercise();

		if (exercise == null)
			return Collections.emptyList();

		String values = getHeartRateValues(exercise);

		List<Short> heartRateList = new ArrayList<Short>();
		for (String value : values.split(",")) {
			heartRateList.add(Short.valueOf(value));
		}
		return heartRateList;
	}

	private String getHeartRateValues(ExerciseData exercise) {
		Result result = exercise.getResult();
		if (result == null || result.getSamples() == null)
			return "";
		List<Sample> samples = result.getSamples().getSample();
		for (Sample sample : samples) {
			if (sample.getType().equals(SampleType.HEARTRATE)) {
				return sample.getValues();
			}
		}
		return "";
	}

}
